/**
 * 
 */
package com.zufangbao.earth.handler.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.JsonUtils;
import com.zufangbao.earth.Constant;
import com.zufangbao.earth.ViewEntry;
import com.zufangbao.earth.handler.CookieHandler;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;


/**
 * Cookie related operations
 * 
 * @author lute
 *
 */
@Component("cookieHandler")
public class CookieHandlerImpl implements CookieHandler {
	
	private static final Log logger = LogFactory.getLog(CookieHandlerImpl.class);
	
	@Value("#{config['ctx.domain']}")
	private String domain;
	
	public void addCookie(String name, String value, HttpServletResponse response) {
		
		logger.info("CookieHandlerImpl#addCookie - add cookie for [" + name + "] with value[" + value + "] in domain[" + this.domain + "].");
		
		Cookie cookieSetting = new Cookie(name, value);
		cookieSetting.setPath("/");
		cookieSetting.setDomain(this.domain);
		cookieSetting.setMaxAge(Constant.DEFAULT_COOKIE_MAX_AGE);
		
		response.addCookie(cookieSetting);
		
	}

	@Override
	public String getCookie(String name, HttpServletRequest request) {
		
		logger.info("CookieHandlerImpl#addCookie - get cookie value for [" + name + "]  in domain[" + this.domain + "].");
		
		Cookie[] cookies = request.getCookies();
		
		for(Cookie cookie : cookies){
			
			if(cookie.getName().equals(name)){
				
				logger.info("CookieHandlerImpl#addCookie - get cookie value["+cookie.getValue()+"] for [" + name + "]  in domain[" + this.domain + "].");
				
				return cookie.getValue();
			}
		}
		
		return StringUtils.EMPTY;
	}
	
	@Override
	public ViewEntry getViewCategoryFromCookie(String name, HttpServletRequest request) {
		
		ViewEntry viewCategory = JsonUtils.parse(getCookie(GlobalSpec4Earth.PARAM_VIEW_CATEGORY, request).toString(),ViewEntry.class);
		
		return viewCategory;
	}

}
